package com.pj.common.base.topbar

import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.annotation.IdRes
import androidx.annotation.StringRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.pj.common.R
import com.pj.common.annotation.LayoutParam
import com.pj.common.base.BaseActivity
import com.pj.common.base.BaseViewModel
import com.pj.common.databinding.ContainBaseTopbarBinding
import com.pj.common.utils.CommonUtils
import com.pj.common.utils.TopBarUtils


open class BaseTopBarActivity<VM : BaseViewModel, T : ViewDataBinding> :
    BaseActivity<VM, ContainBaseTopbarBinding>() {
    protected lateinit var mCBinding: T
    override fun getLayoutRes(): Int = R.layout.contain_base_topbar
    open fun getContentLayout(): Int? = null
    open fun hasBackIcon(): Boolean = true

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        var contentId = getContentLayout()
        var hasBack = hasBackIcon()
        if (contentId == null) {
            var activityParam: LayoutParam = CommonUtils.findAnnotation(javaClass)
                ?: throw IllegalArgumentException("BaseToolBarActivity must has a content layout,and the param layout must not null!")
            contentId = activityParam.layout
            hasBack = activityParam.hasBack
        }
        mCBinding = DataBindingUtil.inflate(
            layoutInflater, contentId,
            mBinding.container, false
        )
        mBinding.topBar.setTitle(title.toString())
        TopBarUtils.initTopBar(mBinding.topBar, hasBack) { onBackPressed() }
        mBinding.container.addView(mCBinding.root)
    }


    /**
     * 手动设置toolbar标题,
     * @param title 默认为空,需要传入resId,不然显示默认值(提示)
     * @param resId StringRes
     */
    fun setToolbarTitle(title: String = "", @StringRes resId: Int = R.string.app_name) {
        supportActionBar?.title = if (title.isEmpty()) getString(resId) else title
    }

    protected fun setToolbarBg(colorString: String) {
        mBinding.topBar.setBackgroundColor(Color.parseColor(colorString))
    }

    protected fun setToolbarBg(@IdRes colorRes: Int) {
        mBinding.topBar.setBackgroundColor(colorRes)
    }

}